from rest_framework import mixins, status
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from cart.models import Cart
from cart.permissions import CartPermissions
from cart.serializers import CartSerializer, ReadCartSerializer


# Create your views here.
class CartView(mixins.ListModelMixin,
               mixins.UpdateModelMixin,
               mixins.CreateModelMixin,
               mixins.DestroyModelMixin,
                        GenericViewSet):
    """添加商品"""
    queryset = Cart.objects.all()
    serializer_class = CartSerializer
    #用户需要登录，每个用户只能修改自己的数据
    permission_classes = [IsAuthenticated,CartPermissions]
    def get_serializer_class(self):
        if self.action=='list':
            return ReadCartSerializer
        else:
            return self.serializer_class
    def create(self, request, *args, **kwargs):
        #获取用户信息
        user=request.user
        # print(user)
        #1、校验该用户的购物车中是否有该商品
        goods=request.data.get('goods')
        if Cart.objects.filter(user=user,goods=goods).exists():
            #这个用户已经添加过该商品到购物车
            cart_goods=Cart.objects.get(user=user, goods=goods)
            # print(cart_goods, request.data)
            cart_goods.number+=1
            cart_goods.save()
            #对该商品进行序列化
            serializer = self.get_serializer(cart_goods)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            #没有商品，则调用父类继承的create方法进行创建
            request.data['user']=user.id
            return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """获取购物车商品列表"""
        query=self.get_queryset().filter(user=request.user)
        serializer=self.get_serializer(query,many=True)

        return Response(serializer.data)
    def update_goods_status(self,request, *args, **kwargs):
        """修改商品选中状态"""
        obj=self.get_object()
        obj.is_checked=not obj.is_checked
        obj.save()
        return Response({'message':'修改成功'},status=status.HTTP_200_OK)
    def updata_goods_number(self,request, *args, **kwargs):
        """修改商品数量"""
        #获取参数
        number=request.data.get('number')
        obj=self.get_object()
        #2、校验参数
        if not isinstance(number,int):
            return Response({'error':'参数不能为空，并且为int类型'},status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        #修改商品数量
        if number <=0 :
            obj.delete()
            return Response({'message': '修改成功,该商品数量为0，已从购物车移除'}, status=status.HTTP_200_OK)
            #删除商品
        elif number>obj.goods.stock:
            return Response({'message': '数量不能超过该商品库存'}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
        else:
            obj.number=number
            obj.save()
            return Response({'message': '修改成功'}, status=status.HTTP_200_OK)


